package me.xujl;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.spring.SpringCamelContext;

import com.alibaba.druid.sql.PagerUtils;
import com.alibaba.druid.util.DruidDataSourceUtils;
import com.alibaba.druid.util.JdbcUtils;

/**
 * User: xujl
 * Date: 8/11/14
 */
public class SQLPaginator {

    private int pageSize = 1000;

    public List<String> split(String sql, String datasourceName, CamelContext camelContext) throws SQLException {
        List<String> sqls = new ArrayList<String>();
        DataSource ds = ((SpringCamelContext) camelContext).getApplicationContext().getBean(datasourceName, DataSource.class);

        String url = DruidDataSourceUtils.getUrl(ds);
        String dbType = JdbcUtils.getDbType(url, null);

        String countSql = PagerUtils.count(sql, dbType);

        List<Map<String, Object>> results = JdbcUtils.executeQuery(ds, countSql);
        Map<String, Object> row = results.get(0);
        Long rows = (Long) row.entrySet().iterator().next().getValue();


        int pageCount = (rows.intValue() / pageSize);
        for (int i = 0; i <= pageCount; i++) {
            String limitSql = PagerUtils.limit(sql, dbType, i * pageSize, pageSize);
            sqls.add(limitSql);
        }

        //sqls.add("SELECT id, register_num, zihao_name, businessman, business_place, business_range, established_date, tel, build_mode, begin_run_date, end_run_date, approval_date, industry_category, reg_dept, register_capital, admin_dept, from_id, credval, credlvl, update_time FROM t_register_personal limit 10");
        //sqls.add("SELECT id, register_num, zihao_name, businessman, business_place, business_range, established_date, tel, build_mode, begin_run_date, end_run_date, approval_date, industry_category, reg_dept, register_capital, admin_dept, from_id, credval, credlvl, update_time FROM t_register_personal limit 10,10");

        return sqls;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
}
